#!/bin/sh
# converts markdown to latex, then uses latex to make a PDF

[ -n "$(which pandoc)" ] || {
    echo >&2 "You need 'pandoc' to use this program!"
    exit 1
}
[ -n "$(which pdflatex)" ] || {
    echo >&2 "You need 'pdflatex' to use this program!"
    exit 1
}

outfile=
for option; do
    if [ -n "$prev" ]; then
	eval "$prev=\$option"
	prev=
	shift
	continue
    fi
    optarg=$(expr "x$option" : 'x[^=]*=\(.*\)')
    case $option in
    -h | --h | --help )
	help=1
	shift ;;
    -o | --o | --output )
	prev=outfile
	shift ;;
    -o=* | --o=* | --output=* )
	outfile=$optarg
	shift ;;
    -* ) echo >&2 "$0: unknown option: $option; aborting"
	exit 1 ;;
    * ) break ;;
    esac
done

[ -z "$help" ] || {
    echo >&2 "Usage: $0 [-o|--output output-file] [input-file]"
    exit 0
}

infile=$1
if [ -z "$outfile" ]; then
    if [ -n "$infile" ]; then
	outfile=${infile%.*}.pdf
    else
	outfile='stdin.pdf' # input is STDIN, since no argument given
    fi
fi

BASE=${outfile##*/}
BASE=${BASE%.*}

set -e

TEMP=${TMPDIR-/tmp}/markdown2pdf.$$
trap "status=$?; rm -rf $TEMP; exit $status" 0 INT
mkdir -p $TEMP

iconv -t utf-8 $infile | pandoc -w latex -s > $TEMP/$BASE.tex  
(
    cd $TEMP
    if ! pdflatex -interaction=batchmode $BASE.tex >/dev/null 2>&1; then
	echo >&2 "LaTeX errors:"
	cat >&2 $BASE.log
	exit 1
    fi
) || exit $?

is_target_exists=
if [ -f $outfile ]; then
    is_target_exists=1
fi

mv --suffix=~ --backup $TEMP/$BASE.pdf $outfile

echo -n >&2 "Created $outfile"
[ -z "$is_target_exists" ] || {
    echo -n >&2 " (previous file has been backed up as '$outfile~')"
}
echo >&2 .
